package net.jueb.protobuf.client;

import net.jueb.protobuf.pojo.ResponseProto;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;

public class ProtobufClient {

	public void connect(String ip,int port)
	{
		NioEventLoopGroup group=new NioEventLoopGroup();
		Bootstrap bt=new Bootstrap();
		bt.group(group);
		bt.channel(NioSocketChannel.class);
		bt.handler(new ChannelInitializer<SocketChannel>() {

			@Override
			protected void initChannel(SocketChannel sc) throws Exception {
				//半包处理
				sc.pipeline().addLast(new ProtobufVarint32FrameDecoder());
				//指定类型的解码器
				sc.pipeline().addLast(new ProtobufDecoder(ResponseProto.Response.getDefaultInstance()));
				
				sc.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
				sc.pipeline().addLast(new ProtobufEncoder());
				
				sc.pipeline().addLast(new ProtoClientHandler());
			}
		});
		try {
			ChannelFuture cf=bt.connect(ip, port).sync();
			cf.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			group.shutdownGracefully();
		}
	}
	public static void main(String[] args) {
		new ProtobufClient().connect("127.0.0.1", 80);
	}
}
